<template>
  <el-dialog
    :title="'开工物料投入口'"
    v-model="dialogVisible"
    width="70%"
    :close-on-click-modal="false"
  >
    <!-- 顶部输入和添加按钮 -->
    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <el-input
        v-model="inputSerial"
        placeholder="请输入序列号"
        style="width: 500px; margin-right: 16px;"
        clearable
      >
        <template #prefix>
          <el-icon><i class="el-icon-qrcode"></i></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">添加</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="serialNo" label="序列号" align="center" />
      <el-table-column prop="materialNo" label="物料编号" align="center" />
      <el-table-column prop="materialName" label="物料名称" align="center" />
      <el-table-column prop="trayNo" label="纤盘号" align="center">
        <template #header>
          <span style="color: orange;">纤盘号</span>
        </template>
      </el-table-column>
      <el-table-column prop="qty" label="数量" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="text" style="color: red;" @click="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部按钮 -->
    <template #footer>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { WorkReportApi, WorkReportVO } from '@/api/opticore/workreport'
import { WorkStartApi } from "@/api/opticore/workstart"
import { ElMessage } from 'element-plus'
import { WorkMaterialRelApi } from "@/api/opticore/workmaterialrel"

interface TableItem {
  id: number
  serialNo: string
  materialNo: string
  materialName: string
  trayNo: string
  qty: number
  parentId: number
  productId:number
}

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({})
  }
})

const dialogVisible = ref(false)
const inputSerial = ref('')
const tableData = ref<TableItem[]>([])
const currentProductId = ref<number | null>(null)
const workStartId = ref<number | null>(null)
// 获取当前登录用户
const currentUser = ref(JSON.parse(localStorage.getItem('userInfo')).nickname)

const emit = defineEmits(['success'])

/** 打开弹窗方法 */
const open = async (params) => {
  // 重置数据
  inputSerial.value = ''
  tableData.value = []
  currentProductId.value = params.productId
  dialogVisible.value = true
  console.log('开工参数:', params)
  console.log('打开弹窗的 productId:', currentProductId.value)
}

/** 添加一行 */
const handleAdd = async () => {
  if (!inputSerial.value) return;
  // 检查序列号是否已存在
  const isSerialNoExist = tableData.value.some(item => item.serialNo === inputSerial.value);
  if (isSerialNoExist) {
    ElMessage.error('序列号已存在');
    return;
  }
  const res = await WorkStartApi.selectInfoBySerialNo(inputSerial.value, currentProductId.value)
  tableData.value.push({
    id: res.id,
    serialNo: inputSerial.value,
    materialNo: res.itemCode,
    materialName: res.itemName,
    trayNo: res.fiberNo,
    qty: res.qty,
    parentId: res.parentId,
    productId:res.productId
  })
  inputSerial.value = ''
}

/** 删除一行 */
const handleDelete = (index: number) => {
  tableData.value.splice(index, 1)
}

/** 确定按钮 */
const handleConfirm = async () => {
  // 检查开工物料投入口是否为空
  if (tableData.value.length === 0) {
    ElMessage.error('请输入物料序列号')
    return
  }
  // 打印每行的 productId 和 currentProductId
  tableData.value.forEach((item, index) => {
    console.log(`第 ${index + 1} 行的 productId: ${item.parentId}, currentProductId: ${currentProductId.value}`)
    console.log(tableData.value);
  })
  // 找出所有 productId 不一致的行号（从1开始）
  const errorRows = tableData.value
    .map((item, idx) => item.parentId !== currentProductId.value ? idx + 1 : null)
    .filter(i => i !== null)
  //这里校验层级关系
  if (errorRows.length > 0) {
    ElMessage.error(`第 ${errorRows.length} 行不是该半成品的物料`)
    return
  }
  //再校验层级关系下 是否满足数量要求 比如 半成品需要两个物料A 一个物料B
  const res = await WorkStartApi.selectInfoByParentId(currentProductId.value);
  console.log(res,"============");  //这里传了 parentId	"1922475511512551426" 和quantity	2.0  在提交的时候需要判断tableData 数量
  const requiredMaterials = res.map(item => ({
    materialId: item.id, // 物料ID
    quantity: item.quantity, // 所需数量
    itemCode:item.itemCode
  }));
  console.log("requiredMaterials",requiredMaterials);
  //统计tableData中productId的总条数
  // 统计 tableData 中每种物料的数量
  const materialCounts = tableData.value.reduce((counts, item) => {
    counts[item.productId] = (counts[item.productId] || 0) + 1;
    return counts;
  }, {} as Record<string, number>);
  console.log("tableData记录",materialCounts);
  // 创建一个物料编号到ID的映射
  const materialIdToItemCode = requiredMaterials.reduce((map, item) => {
    map[item.materialId] = item.itemCode;
    return map;
  }, {} as Record<string, string>);

  // 校验每种物料的数量是否满足要求
  const missingMaterials = requiredMaterials.filter(material => {
    return materialCounts[material.materialId] < material.quantity;
  });
  // 校验是否所有必需的物料都已包含
  const missingMaterialIds = requiredMaterials
    .map(material => material.materialId)
    .filter(materialId => !(materialId in materialCounts));

  // if (missingMaterials.length > 0 || missingMaterialIds.length > 0) {
  //   let errorMessages = [];
  //   if (missingMaterials.length > 0) {
  //     const missingInfo = missingMaterials
  //       .map(mat => `${mat.itemCode}: 需要 ${mat.quantity} 个`)
  //       .join(', ');
  //     errorMessages.push(`物料数量不足: ${missingInfo}`);
  //   }
  //   if (missingMaterialIds.length > 0) {
  //     const missingItemCodes = missingMaterialIds
  //       .map(id => materialIdToItemCode[id] || id)
  //       .join(', ');
  //     errorMessages.push(`缺少必要物料: ${missingItemCodes}`);
  //   }
  //   ElMessage.error(errorMessages.join('; '));
  //   return;
  // }

  if (missingMaterialIds.length > 0) {
    let errorMessages = [];
    const missingItemCodes = missingMaterialIds
      .map(id => materialIdToItemCode[id] || id)
      .join(', ');
    errorMessages.push(`缺少必要物料: ${missingItemCodes}`);
    ElMessage.error(errorMessages.join('; '));
    return;
  }

  try {
    //计算原材料总数
    let qty = 0;
    tableData.value.forEach((item, index) => {
      qty = qty+item.qty;
    })
    // 先创建开工记录
    const workStartRes = await WorkStartApi.createWorkStart({
      serialNo: props.queryParams.serialNo,
      docNo: props.queryParams.docNo,
      lineId: props.queryParams.lineId,
      equipment: props.queryParams.equipment,
      process: props.queryParams.process,
      processCode: props.queryParams.processCode,
      line: props.queryParams.line,
      qty: qty,
      reworkId: Number(props.queryParams.reworkId || 0),
      creator: currentUser.value // 使用当前登录用户
    })
    workStartId.value = workStartRes

    if (!workStartId.value) {
      throw new Error('创建开工记录失败')
    }
    const now = new Date();
    const createTime = now.toISOString().replace('Z', ''); // 去掉时区偏移部分
    // 遍历表格数据，为每行记录创建开工物料关联
    for (const item of tableData.value) {
      await WorkMaterialRelApi.createWorkMaterialRel({

        workId: workStartId.value.toString(),
        inventoryId: item.id.toString(),
        creator: currentUser.value,
        createTime:createTime,
        serialNo: item.serialNo,
      })
    }

    ElMessage.success('开工成功')
    emit('success', {
      tableData: tableData.value,
      workStartId: workStartId.value
    })
    dialogVisible.value = false

    //更新工单表状态  传入开工序列号
    await WorkReportApi.updateWorkReportStatus(props.queryParams.serialNo);
  } catch (error) {
    console.error('保存开工记录失败:', error)
    ElMessage.error('保存开工记录失败')
  }
}

defineExpose({ open })
</script>

<style scoped>
/* 可根据需要自定义样式 */
</style>
